<template>
  <div class="wangeditor-template">
    <div class="view-editor" ref="editor"></div>
    <el-dialog
      title="文件库"
      :visible.sync="filesOpen"
      custom-class="keywordImpt"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      append-to-body
      width="50%"
      v-dialogDrag
    >
      <el-form
        :model="queryParams"
        size="mini"
        ref="queryForm"
        :inline="true"
        @submit.native.prevent
      >
        <el-form-item label="文件名称" prop="keyword">
          <el-input
            v-model="queryParams.keyword"
            placeholder="请输入文件名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="文件类型" prop="fileType">
          <el-select
            v-model="queryParams.fileType"
            clearable
            placeholder="文件类型"
            style="width:140px;"
          >
            <el-option label="图片" value="images"> </el-option>
            <el-option label="视频" value="medias"> </el-option>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
         <el-row :gutter="10" class=" ">
      <el-col :span="1.5">
        <el-button type="primary" plain  icon="el-icon-share" size="mini" @click="handleInputVideos('video')"  >插入视频</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain    icon="el-icon-link" size="mini"  @click="handleInputVideos('link')" >插入超链接</el-button>
      </el-col>

    </el-row>
      <el-table :data="filesData" size="mini" :height="0"   @selection-change="handleSelectionChange">
             <el-table-column type="selection" width="55" align="center" />

        <el-table-column type="index" width="55" align="center" label="序号">

        </el-table-column>
        <el-table-column
          label="文件名"
          prop="fileName"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <i
              :class="
                scope.row.fileType == 'medias'
                  ? 'el-icon-video-play'
                  : scope.row.fileType == 'medias'
                  ? 'el-icon-picture-outline'
                  : 'el-icon-tickets'
              "
            ></i>
            <span style="margin-left: 10px; cursor: default">
              {{ scope.row.fileName }}
            </span>
          </template>
        </el-table-column>

        <el-table-column
          label="上传时间"
          prop="time"
          width="150"
          align="center"
        />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="170"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-share"
              @click="handleinputVideo(scope.row)"
              >插入</el-button
            ><el-button
              size="mini"
              type="text"
              icon="el-icon-link"
              @click="handleinputLink(scope.row)"
              >插入超链接</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getFilesList"
      />
    </el-dialog>
  </div>
</template>

<script>
import { pictureList, pictureRemove, pictureAdd } from "@/api/file/index";
import { formatFileSize } from "@/utils";
import E from "wangeditor-zzb";

import { getToken } from "@/utils/auth";

import { getChannelProp } from "@/api/content/clounm";

import { mapState } from "vuex";

import { FilesMenuClass } from "./files.js";
export default {
  name: "editor",
  props: {
    template: String,
    // imgDetail: Object,
    // 只有 文章编辑里面有传channelId
    channelId: {
      type: [String, Number],
    },
    enterIsP:{
      default:false,
      type:Boolean
    }
  },
  data() {
    return {
      editor: null,
      imgSize: 0,
      videoSize: 0,
      bttpActiveNote: null,
      filesOpen: false,
      filesData: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileType: "",
      },
      total: 0,
      selectFiles:[], // 选中的文件
    };
  },
  computed: {
    ...mapState({
      siteRow: (state) => state.column.siteRow,
      columnRow: (state) => state.column.columnRow,
      city_name: (state) => state.user.city_name,
    }),
  },
  watch: {},
  created() {
    //有栏目的话。上传图片。自动获取栏目图片参数
    this.columnRow?.channelId && this.getChannelDetail();
  },
  async mounted() {
    await this.getConfigKey("sys.editor.imgSize").then((response) => {
      this.imgSize = Number(response.msg);
    });
    await this.getConfigKey("sys.editor.videoSize").then((response) => {
      this.videoSize = Number(response.msg);
      console.log("this.videoSize: ", this.videoSize);
    });
    // 注册菜单
   this.city_name == "dwdt"&& E.registerMenu("filesMenu", FilesMenuClass);
    this.editor = new E(this.$refs.editor); // 实例化富文本编辑器
    this.editor.config.filesMenuClickHook = () => {
      if (this.city_name == "dwdt") {
        this.queryParams.fileType = "medias";
      }
      this.getFilesList();
    };
    // 设置编辑区域高度为 750px
    // this.editor.config.height = 0; // 设置编辑区域高度为 750   px   默认 300
      this.editor.config.height = 750; // 设置编辑区域高度为 750px
    // this.editor.config.enterIsP =true|| this.enterIsP  ; // 回车生成的是 p 还是 br   有bug 不能用
    this.editor.config.pasteFilterStyle = true; // // 过滤样式，默认 true
    // this.editor.config.pasteFilterStyle = false; // // 过滤样式，默认 true
    this.editor.config.pasteIgnoreImg = true; // // 忽略图片，默认 false
    this.editor.config.zIndex = 500; // 设置editor的层级

    // 隐藏菜单栏提示
    this.editor.config.showMenuTooltips = false;
    // 隐藏网络图片
    this.editor.config.showLinkImg = false; // 显示“插入网络图片”
    //菜单配置
    this.editor.config.menus = [
      "AlertMenu",
      "bold", //加粗
      "head", //标题
      "italic", //斜体
      "link", //超链接
      "underline", //下划线
      "strikeThrough", //删除线
      "fontName", //字体
      "fontSize", //字号
      "justify", //对齐
      // "quote",
      "backColor", //背景色
      "foreColor", //字体色
      "imageZzb", //图片
      "video", //视频
      "indent2", //缩进
      // "emoticon",
      "list", //列表
      "lineHeight", //行高
      // "undo",
      // "redo",
      "table", //表格
      // "code",
      "splitLine", //分割线
      // "todo",
    ];

    // 配置粘贴文本的内容处理
    this.editor.config.pasteTextHandle = (pasteStr) => {
      console.log("pasteStr: ", pasteStr);
      // let a = document.createElement("div");
      // a.innerHTML = pasteStr;
      // let b = a.innerText;
      let html = pasteStr
        // .replace(/<table([^>]*)>/g, "")
        // .replace(/<\/table>/g, "")
        // .replace(/<tbody([^>]*)>/g, "")
        // .replace(/<\/tbody>/g, "")
        // .replace(/<tr([^>]*)>/g, "")
        // .replace(/<\/tr>/g, "")
        // .replace(/<td([^>]*)>/g, "")
        // .replace(/<\/td>/g, "")
        // 涉及到自动排版
        .replace(/<br\s*\/?>/gi, '</p><p class="replace"><br>');
      console.log("html: ", html);


          const parser = new DOMParser();
          const doc = parser.parseFromString(html, "text/html");
          // // 获取所有的<script>标签
          const tableTags = doc.querySelectorAll("table");
          // 遍历每个<script>标签，并格式化其中的 JavaScript 代码块
          tableTags.forEach((tableTag) => {
            tableTag.setAttribute('border',0)  ;
            tableTag.setAttribute('width','100%')  ;
            tableTag.setAttribute('cellpadding',0)  ;
            tableTag.setAttribute('cellspacing',0)  ;
          });

          html = doc.body.innerHTML

      return html;
    };

    // 子传父 实时输入数据
    this.editor.config.onchange = (html) => {
      console.log('html: ', html);
      html = html.replaceAll('<!-- <style','<style')
      .replaceAll('</style> -->','</style>')
      // .replaceAll('<style','<!-- <style')
      // .replaceAll('</style>','</style> -->')
      // console.log('html: replaceAll', html);
      this.$emit("editorChange", html);
    };
    // 配置element ui message提示
    this.editor.config.customAlert = (s, t) => {
      console.log("s, t: ", s, t);
      s = s
        .replaceAll("不是图片", "文件格式不正确")
        .replaceAll("不是视频", "文件格式不正确");
      switch (t) {
        case "success":
          this.$message.success(s);
          break;
        case "info":
          this.$message.info(s);
          break;
        case "warning":
          this.$message.warning(s);
          break;
        case "error":
          this.$message.error(s);
          break;
        default:
          this.$message.info(s);
          break;
      }
    };
    // 配置上传图片服务端接口
    this.editor.config.uploadImgServer = `${process.env.VUE_APP_BASE_API}/common/upload`;
    // 1 * 1024 * 1024;   1024M
    this.editor.config.uploadImgMaxSize = this.imgSize * 1024 * 1024; //500M  单位M  2 * 1024 * 1024 // 2M
    //  10 * 1024 * 1024; //10M
    this.editor.config.uploadImgAccept = [
      "jpg",
      "jpeg",
      "png",
      "gif",
      "bmp",
      "jfif",
    ];
    this.editor.config.uploadImgMaxLength = 100; // 设置单张上传 或者多张。  uploadImgMaxLength === 1 ? '' : 'multiple="multiple"'  默认100张
    this.editor.config.uploadFileName = "file"; // formdata中的name属性
    //跨域上传中如果需要传递 cookie 需设置 withCredentials 。
    this.editor.config.withCredentials = true;
    this.editor.config.uploadImgHeaders = {
      Authorization: getToken(), // 设置请求头
      // "Content-Type": "application/x-www-form-urlencoded",
    };
    this.editor.config.uploadImgParams = {
      siteAlias: this.siteRow?.alias || null,
      fileType: "images",
    };
    this.editor.config.uploadImgHooks = {
      // 图片上传并返回结果，但图片插入错误时触发
      fail: function (xhr, editor, result) {
        console.log("error", result);
      },
      success: function (xhr, editor, result) {
        // 图片上传并返回结果，图片插入成功之后触发
        console.log(result, "success");
      },
      // 图片上传并返回了结果，想要自己把图片插入到编辑器中
      customInsert: (insertImgFn, result) => {
        console.log("result: ", result);
        // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
        // insertImgFn 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果

        // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
        const { code, msg, url, realName, storeName } = result;

        if (code == 200) {
          let url2 = url;

          // url2 = url.slice(url.indexOf("/homepage"));
          console.log("🚀 ~ file: index.vue:158 ~ mounted ~ url", url2);
          // if (process.env.NODE_ENV === "development") {
          //   this.$message.error(
          //     "开发环境看不到图片，线上环境通过nginx可以访问，没有ip显示。。"
          //   );
          // }
          // url2 = `${process.env.VUE_APP_BASE_API}/profile/${this.siteRow?.alias}${url}`;

          insertImgFn(url2);
          // result 必须是一个 JSON 格式字符串！！！否则报错
          setTimeout(() => {
            // 图片上传完成就默认一个样式
            let img = document.querySelector(
              `.w-e-text-container img[src="${url2}"]`
            );
            let parentDom = img.parentNode;
            let width = img.width;
            let height = img.height;
            let ratio = width / height;
            let setW = this.imgDetail?.width || width;

            // let setH = 0; // 等比计算
            let setH = "auto" || this.imgDetail?.height || height; // 等比计算
            // if (setW / setH != ratio) {
            //   setH = setW / ratio;
            // }
            img.setAttribute("width", setW);
            img.setAttribute("height", setH);
            img.setAttribute("storename", storeName);
            img.setAttribute("realname", realName);
            img.setAttribute("class", "editor-img");
            parentDom.style.cssText = "text-align: center";
          }, 100);
        } else {
          this.$message.warning("文件上传失败，请检查文件格式");
        }
      },
    };

    if (this.channelId) {
      this.editor.config.imgClickHook = (editor, imgNode) => {
        this.bttpActiveNote = imgNode.elems[0].parentElement;
        let imgAttr = null;
        if (
          imgNode.elems[0].parentElement.className
            .split(/\s/)
            .includes("bttp-active")
        ) {
          imgAttr = {
            storeName: imgNode.elems[0].getAttribute("storename") || "",
            realName: imgNode.elems[0].getAttribute("realname") || "",
            url: imgNode.elems[0].getAttribute("src") || "",
          };
        }

        this.$emit("handleChangeBttp", imgAttr);
      };
    }
    // 配置上传视频服务端接口
    this.editor.config.uploadVideoServer = `${process.env.VUE_APP_BASE_API}/common/upload`;
    // 1 * 1024 * 1024   1024M
    this.editor.config.uploadVideoMaxSize = this.videoSize * 1024 * 1024; //500M  单位M   2 * 1024 * 1024 // 2M
    this.editor.config.uploadVideoAccept = ["flv", "mp4", "avi", "wmv"]; ///视频格式
    this.editor.config.uploadVideoName = "file"; // formdata中的name属性
    //跨域上传中如果需要传递 cookie 需设置 withCredentials 。
    this.editor.config.uploadVideoHeaders = {
      Authorization: getToken(), // 设置请求头
      // "Content-Type": "application/x-www-form-urlencoded",
    };

    this.editor.config.uploadVideoParams = {
      siteAlias: this.siteRow?.alias || null,
      fileType: "medias",
    };
    this.editor.config.uploadVideoHooks = {
      // 图片上传并返回结果，但图片插入错误时触发
      fail: function (xhr, editor, result) {
        console.log("xhr, editor, result: ", xhr, editor, result);
      },
      success: function (xhr, editor, result) {
        // 图片上传并返回结果，图片插入成功之后触发
        console.log(result, "success");
      },
      // 图片上传并返回了结果，想要自己把图片插入到编辑器中
      customInsert: (insertVideoFn, result) => {
        console.log("result: ", result);

        // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
        // insertVideoFn 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果

        // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
        const { code, msg, url, realName, storeName } = result;
        if (code == 200) {
          let url2 = url;

          // url2 = url.slice(url.indexOf("/homepage"));
          // console.log("🚀 ~ file: index.vue:158 ~ mounted ~ url", url);
          // if (process.env.NODE_ENV === "development") {
          //   this.$message.error(
          //     "开发环境看不到图片，线上环境通过nginx可以访问，没有ip显示。。"
          //   );
          // }
          // url2 = `${process.env.VUE_APP_BASE_API}/profile/${this.siteRow?.alias}${url}`;

          insertVideoFn(url2);
          // result 必须是一个 JSON 格式字符串！！！否则报错
return
          setTimeout(() => {
            let video = document.querySelector(
              '.w-e-text-container video[src="' + url + '"]'
            );
            let parentDom = video.parentNode;

            video.setAttribute(
              "width",
              this.city_name == "dwdt" ? "80%" : "50%"
            );

video.innerHTML = '<span>当前浏览器版本过低，无法正常播放视频，请升级您的浏览器。</span>'
            video.setAttribute("class", "editor-video");
            parentDom.style.textAlign = "center";
          }, 100);
        } else {
          this.$message.warning("文件上传失败，请检查文件格式");
        }
      },
    };
// 自定义插入视频
    this.editor.config.customInsertVideo =   (videoUrl) =>{
      console.log('videoUrl: ', videoUrl);

this.handleinputVideo({
fileType:"medias",
url:videoUrl,
})
}

    this.editor.create(); // 创建富文本编辑器
    // setTimeout(() => {
    console.log("文本编辑器初始化默认内容");
     console.log('this.template: ', this.template);
     let t =    this.template.replaceAll('<style','<!-- <style').replaceAll('</style>','</style> -->')

    this.editor.txt.html(t); // 初始化默认内容
    // }, 300);
if (this.city_name == "dwdt") {
        let $menuVideo = document.querySelector('.menu-video')
        $menuVideo.style.display = 'none'
      }
    if (!this.bttpActiveNote) {
      // const imgRegex =
      //   /<p[^>]*class="[^"]*"[^>]*>(?:\s*<img[^>]*alt="[^"]*"[^>]*>\s*)+<\/p>/gi;
      // const parser = new DOMParser();
      // const doc = parser.parseFromString(this.template, "text/html");
      // const matches = doc.body.innerHTML.match(imgRegex);
      // console.log("matches: ", matches);
      this.bttpActiveNote = document.querySelector(".bttp-active") || null;
    }
  },
  watch: {
    value: {
      handler(val) {},
      deep: true,
      immediate: true,
    },
  },
  methods: {
    getChannelDetail() {
      getChannelProp({ channelId: this.columnRow.channelId }).then((res) => {
        this.imgDetail = {
          width: res.data.imgWidth,
          height: res.data.imgHeight,
        };
      });
    },
    /** 获取文件列表 */
    getFilesList() {

      pictureList(this.queryParams.fileType?this.queryParams:  {...this.queryParams,fileType:'medias,images'})
        .then((res) => {
          this.filesData = res.data.list;
          this.total = res.data.totalCount;
        })
        .then(() => {
          this.filesOpen = true;
        });
    },
    handleinputVideo(file) {
      console.log("file: ", file);

      // this.editor.txt.html(this.template)
      if (file.fileType == "medias") {
        let videoDom;
        if (UA == "firefox") {
          videoDom = `<p data-we-video-p="true"><video class="editor-video" src="${file.url}" controls="controls" style="max-width:100%;">
          <span>当前浏览器版本过低，无法正常播放视频，请升级您的浏览器。</span>
          </video></p><p>&#8203</p>`;
           videoDom = `<div class="editor-video-wrap" data-we-video-p="true"><embed class="editor-embed" width="825" height="550" src="${file.url}" autostart="true" loop="true" align="middle" type="video/mp4" style="max-width:100%;">
          </embed></div><p>&#8203</p>`;
        } else {
          videoDom = `<video class="editor-video" src="${file.url}" controls="controls" style="max-width:100%;"><span>当前浏览器版本过低，无法正常播放视频，请升级您的浏览器。</span></video><p data-we-empty-p=""><br></p>`;
          videoDom = `<div class="editor-video-wrap" data-we-video-p="true"><embed class="editor-embed" width="825" height="550" src="${file.url}" autostart="true" loop="true" align="middle" type="video/mp4" style="max-width:100%;"></embed></div><p data-we-empty-p=""><br></p>`;
        }
        this.editor.cmd.do("insertHTML", videoDom);

        // 设置embed样式
        setTimeout(() => {
          let embed = document.querySelectorAll(
            '.editor-embed'
          );
          for (let index = 0; index < embed.length; index++) {
            const it = embed[index];
            let parentDom = it.parentNode;
            // 先直接在embed标签上设置 width="825" height="550"
            // it.setAttribute("width", this.city_name == "dwdt" ? "80%" : "50%");
            it.setAttribute("class", "editor-embed editor-big-embed");


            // parentDom.style.cssText = "text-align: center";
            parentDom.style.textAlign = " center";
          }


// 设置video样式
           let video = document.querySelectorAll(
            '.editor-video'
          );
          console.log("video: ", video);
          for (let index = 0; index < video.length; index++) {
            const it = video[index];
            let parentDom = it.parentNode;
            it.setAttribute("width", this.city_name == "dwdt" ? "80%" : "50%");
            it.setAttribute("class", "editor-video editor-big-video");

            // parentDom.style.cssText = "text-align: center";
            parentDom.style.textAlign = " center";
          }
          this.filesOpen = false;

        }, 100);
      } else if (file.fileType == "images") {
        let imgDom = `<p><img src="${file.url}"  style="max-width:100%;" contenteditable="false"/></p>`;

        this.editor.cmd.do("insertHTML", imgDom);

        setTimeout(() => {
          // 图片上传完成就默认一个样式
          let img = document.querySelector(
            `.w-e-text-container img[src="${file.url}"]`
          );
          let parentDom = img.parentNode;
          let width = img.width;
          let height = img.height;
          let ratio = width / height;
          let setW = this.imgDetail?.width || width;

          // let setH = 0; // 等比计算
          let setH = "auto" || this.imgDetail?.height || height; // 等比计算
          // if (setW / setH != ratio) {
          //   setH = setW / ratio;
          // }
          img.setAttribute("width", setW);
          img.setAttribute("height", setH);
          img.setAttribute("storename", file.filePath);
          img.setAttribute("realname", file.fileName);
          img.setAttribute("class", "editor-img");
          parentDom.style.cssText = "text-align: center";
          this.filesOpen = false;

        }, 100);
      }
    },
    handleinputLink(file) {
      // this.editor.txt.html(this.template)
      let linkDom
      linkDom = `<p data-we-empty-p><a href="${file.url}" target="_blank">${file.fileName}</a></p> <p data-we-empty-p=""><br></p>`
     this.editor.cmd.do('insertHTML', linkDom)


          this.filesOpen = false;

    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getFilesList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectFiles = selection ;
    },
    /**
     * type {String} 插入类型
     */
    handleInputVideos(type){
    for (let index = 0; index < this.selectFiles.length; index++) {
      const file = this.selectFiles[index];
      if(type=='video'){
    this.handleinputVideo(file)
      }else if(type=='link'){
        this.handleinputLink(file)
      }

    }
    },

    typeName(row) {
      console.log("row.fileName: ", row.fileName);
      if (!row.name) return;
      let index = row.fileName.lastIndexOf(".") + 1;
      return row.fileName.slice(index).toLocaleUpperCase();
    },
    fileSize(row) {
      console.log("row: ", row);
      return formatFileSize(+row.fileSize);
      // return row.width + " * " + row.height;
    },
  },
  beforeDestroy() {
    // 销毁编辑器
    this.editor.destroy();
    this.editor = null;
  },
};
</script>

<style scoped lang="scss">
// ::v-deep .w-e-text table td,
// .w-e-text table th {
//   border: #d3d3d3 1px dotted;
// }
//没用滚动条时，需要100% 或者 ova
::v-deep .w-e-text {
  font-size: 16px;
  height: 100%;
  width: 100%;
  // min-height: unset !important;
}
::v-deep .w-e-text-container {
  // flex: 1;
  a, a:focus, a:hover{
    text-decoration: underline;
  }


}
.wangeditor-template{
    flex: 1;
    // overflow: auto;
.view-editor {
    height: 100%;
  display: flex;
  flex-direction: column;
  // overflow: hidden;
  ::v-deep.w-e-toolbar{
    position: sticky;
    top: 0;

// 不要视频菜单
 .menu-video{
  // display: none;
  }
  }
::v-deep .w-e-text-container {
  flex: unset;
  height: 600px;
  height: unset !important;
  min-height: 600px;
}
}
}



::v-deep .bttp-active {
  border: none;
  &:before {
    display: none;
  }
}


::v-deep .editor-video-wrap{
  .editor-embed{
    position:relative;
    z-index:-1;
  }
}

embed{
  border: 1px solid #ccc;
}

::v-deep .keywordImpt {
  // max-height: 80%;
  // min-height: 50%;
  height: 670px;
  .el-form-item__content {
    border: none !important;
    .el-input__inner {
      border: 1px solid #dcdfe6;
      &:focus,
      &:focus-within {
        border: 1px solid #009a94;
      }
    }
  }
  .el-dialog__body{
    display: flex;
flex-direction: column;
height: calc(100% - 50px);

  }
}


</style>
